<?php

namespace app\api\controller;

use lib\libHotUpdate;
use lib\libUploader;
use lib\libVar;
use think\captcha\Captcha;
use think\facade\Request;
use think\DB;
use app\common\validate\Common as CommonValidate;

class Common
{
     //图片上传
    public function uploaderV2()
    {
       
        $option = [
            "isBase64" => FALSE,//是否是base64上传,仅针对图片上传
            "prefix"   => 'v2'//文件名称前缀
        ];
        $obj = new libUploader($option);
        $res = $obj->upload();
        $code = $res['code'];
        $msg = $res['msg'];
        $info = $obj->getFileInfo();
        return json([
            "code" => $code,
            "msg"  => $msg,
            "data" => $info['fileSaveName'],
            "url"  => \tool\Url::FileConversionUrl($info['fileSaveName'])
        ]);
    }
    public function convertedTaoCMD()
    {
        if (!Request::get('setPasswordContent')) {
            return json([
                'code' => 1,
                'data' => '请输入淘口令'
            ]);
        }
        require '../extend/taobao/TopSdk.php';
        $c = new \TopClient;
        $c->appkey = '23344167';
        $c->secretKey = "87e39508f5a8952119ed3a5460c43bef";
        $req = new \WirelessShareTpwdQueryRequest;
        $req->setPasswordContent(Request::get('setPasswordContent'));
        $resp = $c->execute($req);
 
        // $url = 'https://api.open.21ds.cn/apiv1/jiexitkl?apkey=131d7ee7-49bb-e2ba-f167-075406c965ed&kouling=' . urlencode(Request::get('kouling'));
        // $curl = curl_init();
        // curl_setopt($curl, CURLOPT_URL, $url);
        // curl_setopt($curl, CURLOPT_HEADER, 0);
        // curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        // $data = curl_exec($curl);
        // curl_close($curl);
        return json([
            'code' => 0,
            'data' => $resp
        ]);
    }

    public function taobaoProductGet()
    {
        if (!Request::post('url')) {
            return json([
                'code' => 1,
                'data' => '请输入url'
            ]);
        }
        $pattern = "/.*((\?id)|(\&id))=([\d]+)/"; 
        preg_match($pattern, Request::post('url'), $id); 
        // echo '<pre>';
        // print_r($id);
        // echo '</pre>';
        // exit;
        if (empty($id[4])) {
            return json([
                'code' => 1,
                'data' => 'url解析失败'
            ]);
        }
        require '../extend/taobao/TopSdk.php';
        $c = new \TopClient;
        $c->appkey = '23344167';
        $c->secretKey = "87e39508f5a8952119ed3a5460c43bef";
        $req = new \TbkItemInfoGetRequest;
        $req->setNumIids($id[4]);
        $resp = $c->execute($req);
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
        return json([
            'code' => 0,
            'data' => $resp
        ]);
    }
    
    public function open()
    {
        $data = ["code" => 0];
        $data['auth'] = session('?memberInfo');

        $version = DB::name('version')
            ->where('version', Request::get('version'))
            ->where('platform', Request::get('platform'))
            ->find();
        $data['version'] = $version;
        if (!$version || ($version && $version['islastversion'] == 0)) {
            $data['update'] = DB::name('version')
                ->where('islastversion', 1)
                ->where('platform', Request::get('platform'))
                ->find();
        }
        return json($data);
    }

    public function captcha()
    {
        $captcha = new Captcha();
        $captcha->fontSize = 24;
        $captcha->useCurve = false;
        $captcha->length = 4;
        return $captcha->entry();
    }

    public function notice()
    {
        $data = DB::name('notice')
            ->field('noticeid,topic,content,starttime')
            ->where('type', 2)
            ->where('starttime', '<', \tool\Date::date())
            ->where('endtime', '>', \tool\Date::date())
            ->where('status', 1)
            ->order(['starttime' => 'desc'])
            ->limit(20)
            ->select();
        return json(['code' => 0, 'data' => $data]);
    }

    public function notice_detail()
    {
        $data = DB::name('notice')
            ->where('noticeid', Request::get('noticeid'))
            ->where('type', 2)
            ->where('starttime', '<', \tool\Date::date())
            ->where('endtime', '>', \tool\Date::date())
            ->where('status', 1)
            ->find();
        return json(['code' => 0, 'data' => $data]);
    }

    public function base64_upload()
    {
        // $log = app('log')->getLog();
        // app('log')->clear();
        // if (isset($log['info'])) {
        //     $str = $log['info'][4];
        //     $log['info'][4] = substr($str, 0, 80) . '\',\'' . substr($str, strpos($str, 'base64_file_name'));
        //     app('log')->info($log);
        // } else {
        //     app('log')->close();
        // }
        app('log')->close();

        if (!isset($_POST['base64_file'])) {
            return [
                'code' => 1,
                'msg' => '上传文件失败'
            ];
        }

        $subject = str_replace("\n", "", $_POST['base64_file']);
        $pattern = '/^data\:image\/(jpg|jpeg|png|gif);base64,(.*)/';
        preg_match($pattern, $subject, $matches);
        if (!isset($matches[1]) || !in_array($matches[1], ['jpg', 'jpeg', 'png', 'gif'])) {
            return [
                'code' => 1,
                'msg' => '文件类型错误'
            ];
        }
        $base64_data = base64_decode($matches[2]);
        $tmpPath = "/server/app/runtime/tmp/upload/" . uniqid() . '.tmp';
        file_put_contents($tmpPath, $base64_data);
        $_FILES['file'] = [
            'name' => $_POST['base64_file_name'],
            'type' => 'image' . '/' . $matches[1],
            'tmp_name' => $tmpPath,
            'error' => 0,
            'size' => filesize($tmpPath)
        ];

        return $this->upload('base64');
    }

    public function upload($type = '')
    {
        $file = request()->file('file');
        if (!$file) {
            return json([
                'code' => 1,
                'msg' => '上传的文件太大了或者超时了',
            ]);
        }

        if ($type === 'base64') {
            $info = $file->validate(['size' => 1024*1024*32, 'ext' => 'jpg,jpeg,png,gif,mp4'])->move_base64('uploadfile');
        } else {
            $info = $file->validate(['size' => 1024*1024*32, 'ext' => 'jpg,jpeg,png,gif,mp4'])->move('uploadfile');
        }

        if ($info) {
            // DB::name('attachment_buyer')->insert([
            //     'filename' => $info->getInfo('name'),
            //     'filepath' => $info->getPathName(),
            //     'filetype' => $file->getInfo('type'),
            //     'filesize' => $info->getSize(),
            //     'fileext' => $info->getExtension(),
            //     'description' => '',
            //     'isimage' => 1,
            //     'isthumb' => 0,
            //     'userid' => session('?memberInfo.userid') ? : 0,
            //     'uploadtime' => time(),
            //     'uploadip' => Request::ip(),
            // ]);
            header('Access-Control-Allow-Origin: *');
            header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
            header('Access-Control-Allow-Methods: GET, POST, PUT');
            return json([
                "code" => 0,
                "data" => $info->getPathName(),
                "url" => \tool\Url::FileConversionUrl($info->getPathName())
            ]);
        } else {
            return json([
                "code" => 1000,
                "msg" => $file->getError()
            ]);
        }
    }

    public function smsCode()
    {
        $validate = new CommonValidate;
        if (!$validate->scene('smsCode')->check(Request::post())) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }

        if (session('smsCode.time') > 0 && time() - session('smsCode.time') < 60) {
            return json([
                'code' => 1,
                'msg' => '请稍后再试'
            ]);
        }

        $AppKey = '742c0b3aecb9e6a4548d1080c0c90b3f';
        $AppSecret = '721521a6b5d8';
        $p = new \sms\SmsAPI($AppKey, $AppSecret, 'fsockopen');//fsockopen伪造请求
        $cellphone = Request::post('cellphone');
        $result = $p->sendSmsCode('4013419', $cellphone, '', '4');
        if ($result['code'] != 200) {
            return json([
                'code' => 1,
                'errcode' => $result['code'],
                'msg' => $result['msg'],
            ]);
        }

        DB::name('sms_code')->insert([
            'phone' => $cellphone,
            'code' => $result['obj'],
            'time' => \tool\Date::date(),
        ], true);

        session('smsCode', [
            'phone' => $cellphone,
            'code' => $result['obj'],
            'time' => time(),
        ]);

        return json([
            'code' => 0
        ]);
    }

    public function PushMessage()
    {
        $dataList = DB::name('autotask_pushmessage')->where('status', 0)->select();
        foreach ($dataList as $vo) {
            $result = $this->sendPushMessage($vo['userid'], $vo['content']);
            if ($result['status'] == 1) {
                DB::name('autotask_pushmessage')->where('id', $vo['id'])->update(['status' => 1, 'sendtime' => \tool\Date::date()]);
            }
        }
    }

    public function sendPushMessage($userid = 0, $content)
    {
        $msectime = microtime(true) * 10000;
        $appKey = sha1('A6087699780697' . 'UZ' . '88BDC240-8E19-5F29-FF80-29BFF473B42C' . 'UZ' . $msectime) . '.' . $msectime;
        $headers = [
            "X-APICloud-AppId:A6087699780697",
            "X-APICloud-AppKey:{$appKey}",
            "Content-Type:application/json",
        ];
        $postData = [
            'title' => $content,
            'content' => '~',
            'type' => 1,
            'platform' => 0,
            'userIds' => "{$userid}",
        ];
        if ($userid == 0) {
            unset($postData['userIds']);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'https://p.apicloud.com/api/push/message');
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postData));
        $data = curl_exec($curl);
        curl_close($curl);
        return json_decode($data, true);
    }

    //app更新检测
    public function checkAppUpdate()
    {
        $nowVersion = libVar::param("v")->toString();
        //更新标识
        $identify = libVar::param("identify")->toString();
        $identifyArray = [
            "hcm"
        ];
        //白鹿打包的时候有错误，不得已
        if($nowVersion=='3.0.0.202009291'&&!$identify){
        	$identify="bjx";
        }
        if(!$nowVersion || !in_array($identify, $identifyArray)){
            return json([
                'code' => 3,
                'msg'  => "参数错误"
            ]);
        }
        
        $libHot = new libHotUpdate();
        $res = $libHot->checkAppUpdate($nowVersion, $identify);

        if($res == -1){
            return json([
                'code' => 3,
                'msg'  => "不需要更新" //查找不到对应的版本更新目录
            ]);
        }
        if($res === TRUE){
            return json([
                'code' => 2,
                'msg'  => "不需要更新"
            ]);
        }
        $filename = $libHot->getFileName();
        return json([
            'code' => 0,
            "data" => [
                'token'    => $res,
                'filename' => $filename
            ]
        ]);
    }

    //下载热更新文件
    public function downPlug()
    {
    //  return false;
         $token = libVar::param("token")->toString();
        if(!$token){
            return json([
                'code' => 2,
                'msg'  => "token解析错误"
            ]);

        }
        $libHot = new libHotUpdate();
        $path = $libHot->decrypt($token);
        if(!$path){
            exit();

        }
        return $libHot->downLoadFile($path['url'], $path['path']);
    }

}
